package com.kong.configuration;


import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.burgeon.commons.runtime.ThreadContextHolder;
import org.burgeon.commons.unique.*;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


@Controller
@Slf4j
public class LogInterceptor implements HandlerInterceptor {


    @Getter
    private List<String> includePathPatterns = new ArrayList<>();
    @Getter
    private List<String> excludePathPatterns = new ArrayList<>();

    /**
     * logback-spring.xml
     **/
    private static final String TRACE_ID = "TRACE_ID";
    private static final String SERVICE_NAME = "SERVICE_NAME";




    @Value("${spring.application.name}")
    private String serviceName;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String tid = null;
        if (StringUtils.hasText(request.getHeader("TRACE_ID"))) {
            tid = request.getHeader("TRACE_ID");
        }
        if (!StringUtils.hasText(tid)) {
            tid = IDWorker.nextId();
        }
        MDC.put(TRACE_ID, tid);
        MDC.put(SERVICE_NAME, serviceName);
        ThreadContextHolder.setTraceId(tid);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        MDC.remove(TRACE_ID);
        String tid = ThreadContextHolder.getTraceId();
    }


}
